package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.itheima.reggie.common.Result;
import com.itheima.reggie.pojo.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import com.sun.prism.impl.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private  ThreadLocal threadLocal;

    @PostMapping("/add")
    public Result add(@RequestBody ShoppingCart shoppingCart){

        Long id = (Long) threadLocal.get();

        shoppingCart.setUserId(id);

        Long dishId = shoppingCart.getDishId();

        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(ShoppingCart::getUserId,id).eq(ShoppingCart::getDishId,dishId);

        ShoppingCart one = shoppingCartService.getOne(wrapper);

        if (one!=null) {
            one.setNumber(one.getNumber() + 1);
            shoppingCartService.updateById(one);
        }else {
            shoppingCart.setNumber(1);
            shoppingCartService.save(shoppingCart);
        }

        return Result.success("添加成功");

    }

    @GetMapping("/list")
    public Result list(){

        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(ShoppingCart::getUserId,threadLocal.get());

        wrapper.orderByAsc(ShoppingCart::getCreateTime);

        List<ShoppingCart> list = shoppingCartService.list(wrapper);

        return Result.success(list);
    }

    @DeleteMapping("/clean")
    public Result clean(){

        Long currentId = (Long) threadLocal.get();

        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(ShoppingCart::getUserId,currentId);

        shoppingCartService.remove(wrapper);

        return Result.success("清空成功");
    }


    @PostMapping("/sub")
    public Result sub(@RequestBody ShoppingCart shoppingCart){

        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(ShoppingCart::getUserId,threadLocal.get());

        wrapper.eq(shoppingCart.getDishId()!=null,ShoppingCart::getDishId,shoppingCart.getDishId());

        wrapper.eq(shoppingCart.getSetmealId()!=null,ShoppingCart::getSetmealId,shoppingCart.getSetmealId());

        ShoppingCart cart = shoppingCartService.getOne(wrapper);

        if (cart.getNumber()==1)
            shoppingCartService.remove(wrapper);

        cart.setNumber(cart.getNumber()-1);

        shoppingCartService.updateById(cart);

        return Result.success("修改成功");

    }

}
